package com.chuantou.yuba.ui;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.adapter.LocationAdapter;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BDAddressTO;
import com.chuantou.yuba.api.to.BDGeoDataTO;
import com.chuantou.yuba.api.to.BDGeoTO;
import com.chuantou.yuba.api.to.BDPoiLocationTO;
import com.chuantou.yuba.api.to.BDPoiTO;
import com.chuantou.yuba.ui.widget.LoadingView;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.ui.widget.xlist.XListView;
import com.chuantou.yuba.ui.widget.xlist.XListView.IXListViewListener;
import com.chuantou.yuba.util.Constants;

/**
 * 发动态->选取位置界面
 * 
 * @author dl1001
 * 
 */
public class PickLocationActivity extends BaseActionBarActivity implements OnClickListener {
	private XListView mListView;
	private LoadingView mLoadingView;
	private LocationAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		YBApp.get().startLocate(null);
		setContentView(R.layout.pick_location);
		setupViews();
		setTitle(R.string.current_location);
	}

	private void setupViews() {
		mListView = (XListView) findViewById(android.R.id.list);
		mLoadingView = (LoadingView) findViewById(android.R.id.empty);
		mLoadingView.setStyle(Style.LOADING, null);
		mLoadingView.setOnRetryListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				loadPois();
			}
		});
		mListView.setEmptyView(mLoadingView);
		mListView.setXListViewListener(mListViewListener);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				BDPoiTO poi = (BDPoiTO) parent.getItemAtPosition(position);
				Intent data = new Intent();
				data.putExtra(Constants.EXTRA_DATA, poi);
				setResult(RESULT_OK, data);
				finish();
			}
		});
		mListView.setPullLoadEnable(false);
		mAdapter = new LocationAdapter(getApplicationContext());
		mListView.setAdapter(mAdapter);
		loadPois();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		YBApp.get().stopLocate(false);
	}

	private void loadPois() {
		// 先定位
		new AsyncTask<Void, Void, BDLocation>() {
			private CountDownLatch mLatch = new CountDownLatch(1);

			@Override
			protected BDLocation doInBackground(Void... params) {
				BDLocation location = YBApp.get().getLocation();
				try {
					int waitCount = 0;
					while (location == null) {
						mLatch.await(1, TimeUnit.SECONDS);
						location = YBApp.get().getLocation();
						// 10秒后无结果直接返回
						if (waitCount >= 10) {
							break;
						}
						waitCount++;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return location;
			}

			protected void onPostExecute(BDLocation location) {
				if (location != null) {
					startRequest(location.getLongitude(), location.getLatitude());
				} else {
					mLoadingView.setStyle(Style.ERROR, getString(R.string.locate_failed));
				}
			};
		}.execute();

	}

	private void startRequest(final double lng, final double lat) {
		String url = UriHelper.getBaiduGeoPoisUrl(lng, lat);
		GsonRequest<BDGeoDataTO> request = new GsonRequest<BDGeoDataTO>(Method.GET, url, new Listener<BDGeoDataTO>() {

			@Override
			public void onResponse(BDGeoDataTO response) {
				if (!hasDestroyed()) {
					mListView.stopRefresh();
					BDGeoTO geoTO = response == null ? null : response.getGeo();
					if (geoTO == null) {
						mLoadingView.setStyle(Style.ERROR, null);
					} else {
						mAdapter.clear();
						List<BDPoiTO> pois = geoTO.getPois();
						mAdapter.add(pois);
						BDAddressTO address = geoTO.getAddress();
						String formateAddress = geoTO.getFormatedAddress();
						if (address != null && !TextUtils.isEmpty(formateAddress)) {
							String name = TextUtils.isEmpty(address.getDistrict()) ? address.getCity() : address.getDistrict();
							if (!TextUtils.isEmpty(name)) {
								BDPoiTO poiTO = new BDPoiTO();
								poiTO.setAddress(formateAddress);
								BDPoiLocationTO poiLocation = new BDPoiLocationTO();
								poiLocation.setLatitude(lat);
								poiLocation.setLongitude(lng);
								poiTO.setLocation(poiLocation);
								poiTO.setName(name);
								mAdapter.addFirst(poiTO);
							}
						}
						if (mAdapter.getCount() < 1) {
							mLoadingView.setStyle(Style.EMPTY, null);
						}
						mAdapter.notifyDataSetChanged();
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					mListView.stopRefresh();
					mLoadingView.setStyle(Style.ERROR, getString(R.string.locate_failed));
				}
			}
		}, new HashMap<String, String>(), BDGeoDataTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	IXListViewListener mListViewListener = new IXListViewListener() {

		@Override
		public void onRefresh() {
			loadPois();
		}

		@Override
		public void onLoadMore() {
		}
	};

	@Override
	public void onClick(View v) {

	}

	
}
